package com.cily.utils.t_webrtc.conn;

import android.content.Context;

import com.cily.utils.app.event.Event;
import com.cily.utils.log.L;
import com.cily.utils.t_webrtc.Conf;
import com.cily.utils.t_webrtc.utils.ObserverUtils;
import com.zsoft.signala.Connection;
import com.zsoft.signala.transport.StateBase;
import com.zsoft.signala.transport.longpolling.LongPollingTransport;

/**
 * user:cily
 * time:2017/8/12
 * desc:
 */

public class SignalaUtils {
    private final static String TAG = SignalaUtils.class.getSimpleName();
    private static Connection conn;

    private static void conn(Context cx){
        if (conn == null){
            conn = new Connection("http://47.90.73.137:9003/sr", cx, new LongPollingTransport()){
                @Override
                public void OnError(Exception e) {
                    super.OnError(e);
                    L.printException(e);
                }

                @Override
                public void OnMessage(String message) {
                    super.OnMessage(message);
                    L.i(TAG, "OnMessage = " + message);
                    if (ObserverUtils.getInstance().canSend()){
                        Event e = Event.obtain();
                        e.obj =  message;
                        e.what = Conf.WS_MSG;
                        ObserverUtils.getInstance().send(e);
                    }
                }

                @Override
                public void OnStateChanged(StateBase oldState, StateBase newState) {
                    super.OnStateChanged(oldState, newState);
                    L.i(TAG, "****OnStateChanged*****");
                }
            };
        }
    }

    public static void start(Context cx){
        if (conn == null){
            conn(cx);
        }
        if (conn != null){
            conn.Start();
        }
    }

    public static void stop(){
        if (conn != null){
            conn.Stop();
        }
    }
}